<template>
  <div>
    <!-- 导航条区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>活动管理</el-breadcrumb-item>
      <el-breadcrumb-item>活动列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 列表区域 -->
    <el-card>
      <!-- 搜索栏 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <div>
            <el-input placeholder="请输入内容"
                      v-model='state.query'
                      clearable
                      @clear='getuserList'>
              <el-button slot="append"
                         icon="el-icon-search"
                         @click='getuserList'></el-button>
            </el-input>
          </div>
        </el-col>
        <el-col :span="4">
          <el-button type="primary"
                     @click="addDialog=true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 表格 -->
      <el-table :data=usersList
                stripe
                border>
        <el-table-column type='index'></el-table-column>
        <el-table-column prop='username'
                         label="姓名"></el-table-column>
        <el-table-column prop='email'
                         label="邮箱"></el-table-column>
        <el-table-column prop='mobile'
                         label="手机号码"></el-table-column>
        <el-table-column prop='role_name'
                         label="权限"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state"
                       active-color="#13ce66"
                       inactive-color="#ff4949"
                       @change='stateChanged(scope.row)'>
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作"
                         width="180px">
          <template slot-scope="scope">
            <!-- 修改用户信息按钮 -->
            <el-button type="primary"
                       icon="el-icon-edit"
                       size="mini"
                       @click="changeDialogshow(scope.row.id)"></el-button>
            <!-- 删除用户信息按钮 -->
            <el-button type="danger"
                       icon="el-icon-delete"
                       size="mini"
                       @click="deleteUser(scope.row.id)"></el-button>
            <el-tooltip class="item"
                        effect="dark"
                        content="分配角色"
                        placement="top"
                        :enterable='false'>
              <el-button type="warning"
                         icon="el-icon-setting"
                         size="mini"
                         @click="setUserrole(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="state.pagenum"
                     :page-sizes="[1, 2, 5, 10]"
                     :page-size="state.pagesize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total">
      </el-pagination>
      <!-- 添加用户对话框 -->
      <el-dialog title="提示"
                 :visible.sync="addDialog"
                 width="50%"
                 @close='resetForm'>
        <!-- 添加用户表单 -->
        <el-form :model="addForm"
                 :rules="addRules"
                 ref="addFormref"
                 label-width="70px">
          <el-form-item label="用户名"
                        prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码"
                        prop="password">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱"
                        prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机"
                        prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer"
              class="dialog-footer">
          <el-button @click="addDialog = false">取 消</el-button>
          <el-button type="primary"
                     @click="addCheck">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改用户对话框 -->
      <el-dialog title="修改用户信息"
                 :visible.sync="changeDialogVisible"
                 width="50%"
                 @close="closeReset">
        <!-- 修改用户表单 -->
        <el-form :model="changeData"
                 :rules="changeFormRules"
                 ref="changeFormref"
                 label-width="70px">
          <el-form-item label="用户名">
            <el-input v-model="changeData.username"
                      disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱"
                        prop="email">
            <el-input v-model="changeData.email"></el-input>
          </el-form-item>
          <el-form-item label="手机"
                        prop="mobile">
            <el-input v-model="changeData.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer"
              class="dialog-footer">
          <el-button @click="changeDialogVisible = false">取 消</el-button>
          <el-button type="primary"
                     @click="submitForm">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配用户角色对话框 -->
      <el-dialog title="提示"
                 :visible.sync="setuserRole"
                 width="50%"
                 @close='resetSlecte'>
        <div>
          <p>用户名：{{userInfo.username}}</p>
          <p>角色：{{userInfo.role_name}}</p>
          <p>分配新角色：
            <el-select v-model="selectRoleid"
                       placeholder="请选择">
              <el-option v-for="item in roleslist"
                         :key="item.id"
                         :label="item.roleName"
                         :value="item.id">
              </el-option>
            </el-select>
          </p>
        </div>
        <span slot="footer"
              class="dialog-footer">
          <el-button @click="setuserRole = false">取 消</el-button>
          <el-button type="primary"
                     @click="changeuserRole">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>

  </div>
</template>
<script>
export default {
  data () {
    // 邮箱格式校验
    var checkemail = (rule, value, callback) => {
      const email = /^([a-zA-Z0-9._-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (email.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法邮箱'))
    }
    // 手机号格式校验
    var checkmobile = (rule, value, callback) => {
      const mobile = /^1[345678]\d{9}$/
      if (mobile.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法手机号'))
    }
    return {
      state: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      total: 0,
      usersList: [],
      roleslist: [],
      selectRoleid: '',
      addDialog: false,
      // 修改表单数据
      changeData: {},
      changeDialogVisible: false,
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      userInfo: {},
      setuserRole: false,
      // 添加用户表单校验规则
      addRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkemail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkmobile, trigger: 'blur' }
        ]
      },
      // 修改用户表单校验规则
      changeFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkemail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkmobile, trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getuserList()
  },
  methods: {
    getuserList: function () {
      const that = this
      this.$http.get('users', { params: this.state }).then(function (response) {
        that.usersList = response.data.data.users
        that.total = response.data.data.total
      }, function (err) {
        return this.$message.error(err.data.meta)
      })
    },
    handleSizeChange: function (val) {
      this.state.pagesize = val
      this.getuserList()
    },
    handleCurrentChange: function (val) {
      this.state.pagenum = val
      this.getuserList()
    },
    async stateChanged (row) {
      // 发送请求进行状态修改
      const res = await this.$http.put(
        `users/${row.id}/state/${row.mg_state}`
      )
      // 如果返回状态为异常状态则报错并返回
      if (res.data.meta.status !== 200) {
        row.mg_state = !row.mg_state
        return this.$message.error('修改状态失败')
      }
      this.$message.success('更新状态成功')
    },
    // 添加表单数据清空
    resetForm: function () {
      this.$refs.addFormref.resetFields()
    },
    // 添加用户校验
    addCheck: function () {
      const that = this
      this.$http.post('users', this.addForm).then(function (response) {
        if (response.data.meta.status !== 201) {
          that.$message.err('添加用户失败')
        }
        that.$message.success('添加用户成功')
        that.addDialog = false
        that.getuserList()
      }, function (err) {
        console.log(err)
      })
    },
    // 显示修改表单
    changeDialogshow: function (id) {
      const that = this
      this.$http.get('users/' + id).then(function (response) {
        that.changeData = response.data.data
      }, function (err) {
        console.log(err)
      })
      this.changeDialogVisible = true
    },
    closeReset: function () {
      this.$refs.changeFormref.resetFields()
    },
    // 提交校验
    submitForm: function () {
      this.$refs.changeFormref.validate(valid => {
        if (!valid) return
        const that = this
        console.log(that.changeData.email)
        console.log(that.changeData.mobile)
        this.$http.put('users/' + that.changeData.id,
          {
            mobile: that.changeData.mobile,
            email: that.changeData.email
          }
        ).then(function (response) {
          console.log(response)
          if (response.data.meta.status !== 200) {
            that.$message.error('更新用户信息失败')
          }
          that.changeDialogVisible = false
          that.$message.success('更新用户信息成功')
          that.getuserList()
        }, function (err) {
          console.log(err)
        })
      })
    },
    // 删除用户信息
    deleteUser: function (id) {
      this.$confirm('你将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const that = this
        this.$http.delete('users/' + id).then(function (response) {
          console.log(response)
          if (response.data.meta.status !== 200) {
            return that.$message.error('删除用户失败')
          } else {
            that.getuserList()
            that.$message({
              type: 'success',
              message: '删除成功!'
            })
          }
        }, function (err) {
          console.log(err)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 分配用户角色
    setUserrole: function (userinfo) {
      this.userInfo = userinfo
      const that = this
      this.$http.get('roles').then(function (res) {
        if (res.data.meta.status !== 200) {
          that.$message.error('获取用户权限失败')
        }
        that.roleslist = res.data.data
      }, function (err) {
        console.log(err)
      })
      this.setuserRole = true
    },
    changeuserRole: function () {
      const that = this
      this.$http.put(`users/${this.userInfo.id}/role`, { rid: this.selectRoleid }).then(function (res) {
        if (res.data.meta.status !== 200) {
          that.$message.error('更新用户权限失败')
        }
        that.$message.success('更新用户权限成功')
        that.getuserList()
      }, function (err) {
        console.log(err)
      })
      this.setuserRole = false
    },
    resetSlecte: function () {
      this.selectRoleid = ''
    }
  }
}
</script>
<style lang="less" scoped>
.el-breadcrumb {
  margin-bottom: 15px;
  font-size: 15px;
}
.el-card {
  line-height: 0;
}
.el-table {
  margin-top: 15px;
}
</style>
